package cn.bone.auth.security.controller;

import cn.bone.auth.security.base.exception.MyTestException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

    @RequestMapping("/test01")
    @ResponseBody
    public String test01(){
        return "hello test01";
    }

    @RequestMapping("/order")
    @Secured({"ROLE_ORDER"})
    public String order(){
        System.out.println("order");
        printUser();
        return "/order";
    }

    @RequestMapping("/")
    public String index(){
        System.out.println("index");

        printUser();

        return "/index";
    }

    @RequestMapping("/index")
    public String indexPage(){
        System.out.println("indexPage");
        printUser();
        return "/index";
    }

    @RequestMapping("/loginPage")
    public String loginPage(){

        printUser();

        return "/loginPage";
    }

    @RequestMapping("/fail")
    public String fail(){
        return "/fail";
    }

    @RequestMapping("/403")
    public String page403(){
        System.out.println("403");
        return "/403";
    }

    @RequestMapping("/500")
    public String page500(){
        System.out.println("500");
        return "/500";
    }

    @RequestMapping("/myError")
    public String error(){

        throw new MyTestException("自定义的错误");
    }

    private void printUser(){
        //SecurityContextHolder.getContext() 不会为null
        SecurityContext context = SecurityContextHolder.getContext();

        //context.getAuthentication(); 会返回当前认证过的用户，或者匿名用户
        //没有用户登录时，会返回匿名用户（用户名：anonymousUser)
        Authentication authentication = context.getAuthentication();

        if(authentication!=null){
            String name = authentication.getName();
            System.out.println("name: " + name);
        }else {
            //这里不会被执行到
            System.out.println("name: 当前没有用户登录");
        }
    }
}
